import { defineStore } from 'pinia';
import { getMedicalRecordFields } from '@/api/basedata';
import type { 
  MedicalRecordField, 
  MedicalRecordFieldData,
  FieldTreeNode,
  FlatFieldTreeNode,
  FieldScope,
  FieldType,
  YesNoFlag
} from '@/types/medicalRecordField';
import { 
  findFieldById,
  findFieldByCode,
  searchFields,
  filterFieldsByScope,
  filterFieldsByType,
  getRequiredFields,
  getRecommendedFields,
  flattenFieldTree,
  getFieldStats,
  findTreeNodeByValue
} from '@/types/medicalRecordField';

interface MedicalRecordFieldState {
  /** 医疗记录字段数据 */
  fieldData: MedicalRecordFieldData | null;
  /** 西医字段列表 */
  westernFields: MedicalRecordField[];
  /** 中医字段列表 */
  chineseFields: MedicalRecordField[];
  /** 扁平化的字段树节点（所有字段的选项） */
  flatFieldOptions: FlatFieldTreeNode[];
  /** 加载状态 */
  loading: boolean;
  /** 错误信息 */
  error: string | null;
  /** 最后更新时间 */
  lastUpdated: number | null;
}

export const useMedicalRecordFieldStore = defineStore('medicalRecordField', {
  state: (): MedicalRecordFieldState => ({
    fieldData: null,
    westernFields: [],
    chineseFields: [],
    flatFieldOptions: [],
    loading: false,
    error: null,
    lastUpdated: null,
  }),

  getters: {
    // 获取所有字段（西医+中医）
    getAllFields: (state) => [...state.westernFields, ...state.chineseFields],

    // 获取西医字段
    getWesternFields: (state) => state.westernFields,

    // 获取中医字段
    getChineseFields: (state) => state.chineseFields,

    // 获取必填字段
    getRequiredWesternFields: (state) => getRequiredFields(state.westernFields),
    getRequiredChineseFields: (state) => getRequiredFields(state.chineseFields),
    getAllRequiredFields(): MedicalRecordField[] {
      return [...this.getRequiredWesternFields, ...this.getRequiredChineseFields];
    },

    // 获取推荐字段
    getRecommendedWesternFields: (state) => getRecommendedFields(state.westernFields),
    getRecommendedChineseFields: (state) => getRecommendedFields(state.chineseFields),
    getAllRecommendedFields(): MedicalRecordField[] {
      return [...this.getRecommendedWesternFields, ...this.getRecommendedChineseFields];
    },

    // 获取支持语音的字段
    getVoiceEnabledFields: (state) => 
      state.westernFields.concat(state.chineseFields)
        .filter(field => field.isVoice === '1'),

    // 获取支持图片的字段
    getImageEnabledFields: (state) => 
      state.westernFields.concat(state.chineseFields)
        .filter(field => field.isImage === '1'),

    // 获取支持脉搏的字段
    getPulseEnabledFields: (state) => 
      state.westernFields.concat(state.chineseFields)
        .filter(field => field.isPulse === '1'),

    // 获取周期性字段
    getCyclicFields: (state) => 
      state.westernFields.concat(state.chineseFields)
        .filter(field => field.isCycle === '1'),

    // 根据字段类型分组
    getFieldsByType: (state) => (type: FieldType) => 
      filterFieldsByType([...state.westernFields, ...state.chineseFields], type),

    // 获取字段统计信息
    getFieldStats: (state) => {
      if (!state.fieldData) return null;
      return getFieldStats(state.fieldData);
    },

    // 检查数据是否已加载
    isDataLoaded: (state) => state.fieldData !== null && !state.loading,

    // 检查数据是否需要刷新（超过1小时）
    needsRefresh: (state) => {
      if (!state.lastUpdated) return true;
      const oneHour = 60 * 60 * 1000;
      return Date.now() - state.lastUpdated > oneHour;
    },
  },

  actions: {
    // 获取医疗记录字段数据
    async fetchMedicalRecordFields(force = false) {
      // 如果数据已存在且不强制刷新，直接返回
      if (!force && this.fieldData && !this.needsRefresh) {
        return this.fieldData;
      }

      this.loading = true;
      this.error = null;

      try {
        const response = await getMedicalRecordFields();
        
        if (response.code === '200') {
          this.fieldData = response.data;
          this.westernFields = response.data.westernList;
          this.chineseFields = response.data.chineseList;
          
          // 生成扁平化的字段选项
          this.generateFlatFieldOptions();
          
          this.lastUpdated = Date.now();
          this.error = null;
        } else {
          this.error =  '获取医疗记录字段失败';
        }

        return this.fieldData;
      } catch (error) {
        this.error = error instanceof Error ? error.message : '获取医疗记录字段失败';
        //console.error('获取医疗记录字段失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 生成扁平化的字段选项
    generateFlatFieldOptions() {
      const allOptions: FlatFieldTreeNode[] = [];
      
      [...this.westernFields, ...this.chineseFields].forEach(field => {
        if (field.treeList && field.treeList.length > 0) {
          const flatOptions = flattenFieldTree(field.treeList);
          allOptions.push(...flatOptions);
        }
      });
      
      this.flatFieldOptions = allOptions;
    },

    // 根据字段ID查找字段
    findFieldById(fieldId: number): MedicalRecordField | undefined {
      const allFields = [...this.westernFields, ...this.chineseFields];
      return findFieldById(allFields, fieldId);
    },

    // 根据字段代码查找字段
    findFieldByCode(fieldCode: string): MedicalRecordField | undefined {
      const allFields = [...this.westernFields, ...this.chineseFields];
      return findFieldByCode(allFields, fieldCode);
    },

    // 搜索字段
    searchFields(keyword: string, scope?: FieldScope): MedicalRecordField[] {
      let fields: MedicalRecordField[] = [];
      
      if (scope === '2') {
        fields = this.westernFields;
      } else if (scope === '3') {
        fields = this.chineseFields;
      } else {
        fields = [...this.westernFields, ...this.chineseFields];
      }
      
      return searchFields(fields, keyword);
    },

    // 根据范围获取字段
    getFieldsByScope(scope: FieldScope): MedicalRecordField[] {
      const allFields = [...this.westernFields, ...this.chineseFields];
      return filterFieldsByScope(allFields, scope);
    },

    // 根据字段ID获取字段选项
    getFieldOptions(fieldId: number): FieldTreeNode[] {
      const field = this.findFieldById(fieldId);
      return field?.treeList || [];
    },

    // 根据值查找选项节点
    findOptionByValue(fieldId: number, value: string): FieldTreeNode | undefined {
      const options = this.getFieldOptions(fieldId);
      return findTreeNodeByValue(options, value);
    },

    // 获取字段的所有选项值（扁平化）
    getFieldAllOptions(fieldId: number): FlatFieldTreeNode[] {
      const field = this.findFieldById(fieldId);
      if (!field?.treeList) return [];
      
      return flattenFieldTree(field.treeList);
    },

    // 搜索字段选项
    searchFieldOptions(fieldId: number, keyword: string): FlatFieldTreeNode[] {
      const allOptions = this.getFieldAllOptions(fieldId);
      
      if (!keyword.trim()) return allOptions;
      
      const lowerKeyword = keyword.toLowerCase();
      return allOptions.filter(option => 
        option.text.toLowerCase().includes(lowerKeyword) ||
        option.value.toLowerCase().includes(lowerKeyword) ||
        option.fullPath.toLowerCase().includes(lowerKeyword)
      );
    },

    // 批量获取字段信息
    getFieldsByIds(fieldIds: number[]): MedicalRecordField[] {
      return fieldIds.map(id => this.findFieldById(id)).filter(Boolean) as MedicalRecordField[];
    },

    // 批量获取字段信息（按代码）
    getFieldsByCodes(fieldCodes: string[]): MedicalRecordField[] {
      return fieldCodes.map(code => this.findFieldByCode(code)).filter(Boolean) as MedicalRecordField[];
    },

    // 检查字段是否必填
    isFieldRequired(fieldId: number): boolean {
      const field = this.findFieldById(fieldId);
      return field?.isRequired === '1';
    },

    // 检查字段是否推荐
    isFieldRecommended(fieldId: number): boolean {
      const field = this.findFieldById(fieldId);
      return field?.isRecom === '1';
    },

    // 检查字段是否支持语音
    isFieldVoiceEnabled(fieldId: number): boolean {
      const field = this.findFieldById(fieldId);
      return field?.isVoice === '1';
    },

    // 检查字段是否支持图片
    isFieldImageEnabled(fieldId: number): boolean {
      const field = this.findFieldById(fieldId);
      return field?.isImage === '1';
    },

    // 获取字段的默认值或推荐选项
    getFieldRecommendedOptions(fieldId: number): FieldTreeNode[] {
      const field = this.findFieldById(fieldId);
      if (!field?.treeList) return [];

      // 优先返回被标记为必填的选项（isDefault === 1/'1'/true），支持整棵树
      const required: FieldTreeNode[] = [];
      const dfs = (nodes: FieldTreeNode[]) => {
        for (const node of nodes) {
          const isReq = (node as any).isDefault === '1' || (node as any).isDefault === 1 || (node as any).isDefault === true;
          if (isReq) required.push(node);
          const children = (node as any).children as FieldTreeNode[] | undefined;
          if (children && children.length) dfs(children);
        }
      };
      dfs(field.treeList);

      if (required.length > 0) return required;

      // 若没有标记必填的节点，则回退为所有顶级选项
      return field.treeList.filter((option: any) => option.parentId === 0);
    },

    // 清空数据
    clearData() {
      this.fieldData = null;
      this.westernFields = [];
      this.chineseFields = [];
      this.flatFieldOptions = [];
      this.error = null;
      this.lastUpdated = null;
    },

    // 重置状态
    resetState() {
      this.clearData();
      this.loading = false;
    },

    // 刷新数据
    async refreshData() {
      return this.fetchMedicalRecordFields(true);
    },
  },
});
